//
//  NetWork.swift
//  WeiBoDemo
//
//  Created by chaowen deng on 2021/3/26.
//

import SwiftUI

struct NetWork: View {
    
    @State private var text = "文本显示器"
    var body: some View {
        
        VStack {
            
            Text(text).font(.title)
            
            Button(action: {
                self.startLoad()
            }, label: {
                Text("Start").font(.largeTitle)
            })
            
            
            
            Button(action: {
                self.text = ""
            }, label: {
                Text("Clear").font(.largeTitle)
            })
            
        }
    }
    
    func startLoad() {
        
        NetworkAPI.recommendPostList { result in
            switch result {
            case let .success(list): self.updateText("一共有\(list.list.count)条数据")
            case let .failure(error): self.updateText(error.localizedDescription)
            }
        }
        
        NetworkAPI.hotPostList { result in
            switch result {
            case let .success(list): self.updateText("一共有\(list.list.count)条数据")
            case let .failure(error): self.updateText(error.localizedDescription)
            }
        }
        
        /*
//        let url =  "https://github.com/xiaoyouxinqing/PostDemo/raw/master/PostDemo/Resources/PostListData_recommend_1.json"
        //WeiBoDemo/WeiBoDemo/Resources/PostListData_hot_1.json
        
        // _ = NetWorkManager.shared.requestGet 赋值给忽略变量，取消 调用方法，却没使用返回值的警告
        NetWorkManager.shared.requestGet(path: "PostListData_recommend_1.json", parameters: nil) { result in
            switch result {
            case let .success(data):
                // Handle data
                guard let list = try? JSONDecoder().decode(PostList.self, from: data) else {
                    self.updateText("无法解析数据")
                    return
                }
                
                self.updateText("一共有\(list.list.count)条数据")
                
                break
                
            case let .failure(error):
                // Handle error
                self.updateText(error.localizedDescription)
                break
            }
        }
 */
        /*
        AF.request(url).responseData { response in
            switch response.result {
            case let .success(data):
                // Handle data
                guard let list = try? JSONDecoder().decode(PostList.self, from: data) else {
                    self.updateText("无法解析数据")
                    return
                }
                
                self.updateText("一共有\(list.list.count)条数据")
                
                break
                
            case let .failure(error):
                // Handle error
                self.updateText(error.localizedDescription)
                break
            }
        }
        */
    }
    
    
    /*
    func startLoad() {
        let url = URL(string: "https://github.com/xiaoyouxinqing/PostDemo/raw/master/PostDemo/Resources/PostListData_recommend_1.json")!
        //WeiBoDemo/WeiBoDemo/Resources/PostListData_hot_1.json
        
        var request = URLRequest(url: url)
        request.timeoutInterval = 15.0
        
//        request.httpMethod = "POST"
//        let dic = ["key":"value"]
//        let data = try! JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
//        request.httpBody = data
//        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                self.updateText(error.localizedDescription)
                return
            }
            
            guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
                self.updateText("Invalid response")
                return
            }
            
            guard let data = data else {
                self.updateText("No data")
                return
            }
            
            guard let list = try? JSONDecoder().decode(PostList.self, from: data) else {
                self.updateText("无法解析数据")
                return
            }
            
            self.updateText("一共有\(list.list.count)条数据")
        }
        task.resume()
    }
 */
    
    
    func updateText(_ text: String) {
        DispatchQueue.main.async {
            self.text = text
        }
    }
}

struct NetWork_Previews: PreviewProvider {
    static var previews: some View {
        NetWork()
    }
}
